#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <winsock.h>
#include "asgka.h"

#pragma comment(lib, "ws2_32")

using namespace std;
typedef map<string, unsigned long> msu;

void CharsToSUMap(const char *buf, msu &sump);
void StrVectorToChars(const vector<string> &vec, char *buf);

int main()
{
	char *members = new char[1024];
	char localname[] = "whuyinpeng";
	ASGKASetup(localname);
	Sleep(500);
	ASGKASearch();
	Sleep(1000);
	ASGKAGetAllMember(members);
	msu mmberl;
	CharsToSUMap(members, mmberl);

	msu::iterator it = mmberl.begin();
	for (; it != mmberl.end(); it++)
	{
		cout << it->first << endl;
		in_addr temp; 
		cout << (long)it->second << endl;
		temp.S_un.S_addr = it->second;
		cout << (long)(temp.S_un.S_addr) << endl;
		cout << inet_ntoa(temp) << endl;
	}

	/*vector<string> gmembers;
	gmembers.insert(gmembers.begin(), "yinpeng");
	StrVectorToChars(gmembers, members);
	ASGKACreateGroup("whuyinpeng'sGroup", members);

	getchar();
	ASGKAKickOut("whuyinpeng'sGroup", "yinpeng");

	memset(members, 0, 1024);
	ASGKAGetAllMember(members);
	mmberl.clear();
	CharsToSUMap(members, mmberl);

	it = mmberl.begin();
	for (; it != mmberl.end(); it++)
	{
		cout << it->first << endl;
		in_addr temp; 
		temp.S_un.S_addr = htonl(it->second);
		cout << inet_ntoa(temp) << endl;
	}

	getchar();
	ASGKAAddMember("whuyinpeng'sGroup", "yinpeng");*/

	getchar();
	ASGKAClose();
	getchar();
	ASGKASetup(localname);
	Sleep(500);
	ASGKASearch();
	Sleep(1000);
	getchar();
	ASGKAClose();
	return 0;
}

void StrVectorToChars(const vector<string> &vec, char *buf)
{
	string temp;
	temp.clear();
	int length = vec.size();
	temp.append((char *)&length, 4);

	vector<string>::const_iterator it = vec.begin();
	for (it; it != vec.end(); it++)
	{
		int nlen = it->size();
		temp.append((char *)&nlen, 4);
		temp.append((*it).c_str(), it->size());
	}

	memcpy(buf, temp.c_str(), temp.size());
}

void CharsToSUMap(const char *buf, msu &sump)
{
	int i = 0;
	int length = *((int *)(buf + i));
	i += 4;
	string temp;
	unsigned long netaddr;

	for (int k = 0; k < length; k++)
	{
		int strlen = *((int *)(buf + i));
		i += 4;
		temp.clear();
		temp.append(buf + i, strlen);
		i += strlen;
		netaddr = *((unsigned long *)(buf + i));
		i += 4;
		sump.insert((msu::value_type(temp, netaddr)));
	}
}
